package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.api.article.IArticleClient;
import com.heima.common.test4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.Aliyunutil.textcheck;
import com.heima.wemedia.Aliyunutil.textimage;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Override
    @Async
    public void autoScanWmNews(Integer id) {
        WmNews wmNews = wmNewsMapper.selectById(id);
        //判断查询出来的wmnew是否为空
        if(wmNews == null){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            //从内容中提取纯文本内容和图片
            Map<String,Object> resuiltmap = handleTextAndImages(wmNews);
//            去阿里云审核内容
            String content = (String)resuiltmap.get("content");
           Boolean maybe =  checkintext(content,wmNews);
           if (!maybe) return;
           //自定义敏感词
            boolean isSensitive = handleSensitiveScan((String) resuiltmap.get("content"), wmNews);
            if(!isSensitive) return;
           //阿里云审核图片
            ArrayList<String> images = (ArrayList<String>)resuiltmap.get("images");
            Boolean maybeimage = checkinimages(images, wmNews);
            if (!maybeimage){
                return;
            }
            //4.审核成功，保存app端的相关的文章数据
            ResponseResult responseResult =saveAppArticle(wmNews);
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews,(short) 9,"审核成功");
        }
    }
    @Autowired
    WmSensitiveMapper wmSensitiveMapper;
    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        boolean flag = true;
        List<WmSensitive> wmSensitives =
                wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitivelist =
                wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        SensitiveWordUtil.initMap(sensitivelist);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if(map.size() >0){
            updateWmNews(wmNews,(short) 2,"当前文章中存在违规内容"+map);
            flag = false;
        }

        return flag;
    }

    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private IArticleClient articleClient;
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        //属性的拷贝
        BeanUtils.copyProperties(wmNews,dto);
        //文章的布局
        dto.setLayout(wmNews.getType());
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(wmChannel != null){
            dto.setChannelName(wmChannel.getName());
        }
        //作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        dto.setAuthorName(wmUser.getName());
        //设置文章id
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());
        ResponseResult responseResult = articleClient.saveArticle(dto);
        return responseResult;
    }

    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private Tess4jClient tess4jClient;
    private Boolean checkinimages(ArrayList<String> images, WmNews wmNews) {
        boolean flag = true;
        if(images == null || images.size() == 0){
            return flag;
        }
        List<String> singlelist = images.stream().distinct().collect(Collectors.toList());
//        分开判断先判断是否符合本地校验规则
        try {
            for (String image : singlelist) {
                URL url = new URL(image);
                BufferedImage read = ImageIO.read(url);
                String s = tess4jClient.doOCR(read);
                Boolean checkintext = handleSensitiveScan(s, wmNews);
                if (!checkintext){
                    return checkintext;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        for (String image : singlelist) {
            try {
                String suggestion = textimage.testimage(image);
                if ("block".equals(suggestion)){
                    flag = false;
                    updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
                }
                if ("review".equals(suggestion)){
                    flag = false;
                    updateWmNews(wmNews, (short) 3, "当前文章中存在不确定内容");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return flag;
            }
        }
        return flag;
    }

    private Boolean checkintext(String content, WmNews wmNews) {
        boolean flag =true;
        if ((wmNews.getTitle()+content).length() == 0){
            return flag;
        }
        try {
            String idea = textcheck.theone(content);
            System.out.println(idea);
            if ("block".equals(idea)){
                flag =false;
                updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容");
            }
            if ("review".equals(idea)){
                updateWmNews(wmNews,(short) 3,"当前文章存在不确定的内容");
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return  flag;
    }

    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        // 从wmnews中提取文本和图片
        StringBuffer textResult = new StringBuffer("");
        ArrayList<String> imagesResult = new ArrayList<>();  // 注意变量名是imagesResult（大写R）
        String textAndImage = wmNews.getContent();

        if (StringUtils.isNotBlank(textAndImage)) {
            // 解析JSON数组为List<Map>
            // 使用TypeReference解决泛型类型不匹配问题
            List<Map<String, Object>> contentList = JSONArray.parseObject(
                    textAndImage,
                    new TypeReference<List<Map<String, Object>>>() {}
            );

            for (Map<String, Object> item : contentList) {
                // 获取当前元素的类型（image或text）
                String type = (String) item.get("type");
                // 获取对应的值
                String value = (String) item.get("value");

                if ("text".equals(type)) {
                    // 文本类型：追加到StringBuffer
                    textResult.append(value);
                } else if ("image".equals(type)) {
                    // 图片类型：添加到图片列表
                    imagesResult.add(value);
                }
            }
        }

        // 提取文章的封面图片
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            String[] split = wmNews.getImages().split(",");
            imagesResult.addAll(Arrays.asList(split));  // 修复：imagesresult -> imagesResult
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", textResult.toString());  // 修复：textresult -> textResult
        resultMap.put("images", imagesResult);  // 修复：imagesresult -> imagesResult
        return resultMap;
    }

}
